<template>
  <div class="mint mgt-20 flex-s-between-start">
    <!--left  upload image -->
    <div class="mint_left flex-1">
      <div class="fontW-b theme-color font-45">{{$t('imeet.mint.title')}}</div>
      <div class="upload mgt-20">
        <img v-if="mintWorkUrl" :src="mintWorkUrl" alt="" class="uploaded-picture">
        <upload v-else :maxsize="maxsize" :from="fromMint" @getImgUrl="getImgUrl"/>
      </div>
      <div class="uploadTips color-f mgt-20">
        <p class="fontW-b font-20">Image, Video, Audio, or 3D Model</p>
        <p class="mgt-10 font-10">File types supported: JPG, PNG, GIF, SVG, MP4, WEBM, MP3, WAV, OGG, GLB, GLTF. Max size: 100 MB</p>
      </div>
    </div>
    <!--right inputs -->
    <div class="mint_right flex-1">
      <div class="art_item">
        <div class="fontW-b theme-color font-25">{{$t('imeet.mint.name')}}</div>
        <div class="inputItem bg-5d border-r boxS-i-4 mgt-10 pdlr-10 h-37">
          <input class="color-d6 font-14" :placeholder="$t('imeet.mint.name_placeholder')" v-model="MintName" type="text">
        </div>
      </div>
      <div class="art_item">
        <div class="fontW-b theme-color font-25">{{$t('imeet.mint.desc')}}</div>
        <div class="inputItem bg-5d border-r boxS-i-4 mgt-10">
          <el-input
            type="textarea"
            :rows="4"
            :placeholder="$t('imeet.mint.desc_placehoilder')"
            v-model="MintDesc">
          </el-input>
        </div>
      </div>
      <!-- <div class="art_item">
        <div class="fontW-b theme-color font-25">{{$t('imeet.mint.collection')}}</div>
        <div class="inputItem bg-5d border-r boxS-i-4 mgt-10 h-37">
          <Select :options="selectData" @getSelectVal="getSelectVal"/>
        </div>
      </div> -->
      <div class="mgt-10 flex-s-between">
        <div class="flex-1">
          <div class="fontW-b theme-color font-25">{{$t('sell.chain')}}</div>
          <div class="bg-5d border-r boxS-i-4 h-37" v-if="selectData.length > 0">
            <Select :options="selectData" @getSelectVal="getSelectVal"/>
          </div>
        </div>
        <div class="flex-1 mgl-20">
          <div class="fontW-b theme-color font-25">{{$t('imeet.mint.agreement')}}</div>
          <div class="bg-5d border-r boxS-i-4 h-37">
            <Select :options="agreementData" @getSelectVal="getSelectValue"/>
          </div>
        </div>
      </div>
      <div class="mgt-10 flex-s-between">
        <div class="flex-1">
          <div class="fontW-b theme-color font-25">{{$t('imeet.mint.choose_class')}}</div>
          <div class="bg-5d border-r boxS-i-4 h-37">
            <!-- <Select :options="$t('imeet.mint.choose_type')" @getSelectVal="getSelectVal"/> -->
            <Select :options="classData" @getSelectVal="getClassSelectVal"/>
          </div>
        </div>
        <div class="flex-1 mgl-20">
          <div class="fontW-b theme-color font-25">{{$t('imeet.mint.mint_num')}}</div>
          <div class="bg-5d border-r boxS-i-4 h-37">
            <!-- <Select :options="selectData" @getSelectVal="getSelectVal"/> -->
            <input class="color-d6 font-14 pdlr-10" ref="mintNum" :placeholder="$t('imeet.mint.mint_num')" v-model="MintNum" @blur="checkMintNum" type="text">
          </div>
        </div>
      </div>
      <div class="mgt-10 flex-s-between-start">
        <div class="" style="width:50%;">
          <div class="fontW-b theme-color font-25">{{$t('imeet.mint.characteristics')}}</div>
          <div v-for="(item, i) in typeData" :key="i" class="h-37 mgt-5">
            <div class="flex-s-between">
              <div class="bg-5d border-lb-5 boxS-i-4 flex-1 pdlr-10">
                <input class="color-d6 font-14" v-model="item.trait_type" type="text" :placeholder="$t('title.type')">
              </div>
              <div class="bg-5d border-rt-5 boxS-i-4 flex-left-nowrap flex-2 mgl-5 pdl-10">
                <input class="border_r-1 color-d6 font-14" v-model="item.value" type="text" :placeholder="$t('imeet.mint.name')">
                <div v-if="item.addFlag" @click="addTypeItem">
                  <i class="el-icon-plus fontW-9 color-9e pdlr-10 font-14"></i>
                </div>
                <div v-else @click="delTypeItem(item, i)">
                  <i class="el-icon-minus fontW-9 color-9e pdlr-10 font-14"></i>
                </div>
              </div>
            </div>
          </div>
        </div>
        <!-- <div class="flex-1 mgl-20">
          <div class="fontW-b theme-color font-25">{{$t('imeet.mint.level')}}</div>
          <div v-for="(item, i) in leavelData" :key="i" class="h-37 mgt-5">
            <div class="flex-s-between">
              <div class="bg-5d border-lb-5 boxS-i-4 flex-1 pdlr-10">
                <input v-model="item.type" type="text" :placeholder="$t('title.type')">
              </div>
              <div class="bg-5d border-rt-5 boxS-i-4 flex-left-nowrap flex-2 mgl-5">
                <div class="border_r-1 flex  pdlr-5">
                  <input class="bg-d8 boxS-i-4 border-r text-c" v-model="item.minNum" type="text" :placeholder="$t('imeet.mint.name')">
                  <span class="pdlr-10 color-d6">of</span>
                  <input class="bg-d8 boxS-i-4 border-r text-c" v-model="item.maxNum" type="text" :placeholder="$t('imeet.mint.name')">
                </div>
                <div v-if="item.addFlag" @click="addLeavelItem">
                  <i class="el-icon-plus fontW-9 color-9e pdlr-10 font-14"></i>
                </div>
                <div v-else @click="delLeavelItem(item, i)">
                  <i class="el-icon-minus fontW-9 color-9e pdlr-10 font-14"></i>
                </div>
              </div>
            </div>
          </div>
        </div> -->
      </div>
      <div class="mint_btn bmg_tb10 flex-s-between">
        <div class="mint_btn_item flex-1">
          <el-button
          class="color-0 bg-theme fontW-7 font-28 box-4 flex-1"
          type="primary" @click="hundleCreate(0)">{{ $t("btn.mint_creat") }}</el-button>
        </div>
        <div class="mint_btn_item flex-1 mgl-20">
          <el-button
          class="color-0 bg-theme fontW-7 font-28 box-4 flex-1"
          type="primary" @click="hundleCreate(1)">{{ $t("btn.mint_creatandsell") }}</el-button>
        </div>
      </div>
    </div>
  </div>
</template>
<script>
import Upload from '../../components/component/Upload'
import DropDown from '../../components/component/Dropdown'
import Select from '../../components/component/Select'
import { Message } from 'element-ui'

import {initContract, initWeb3} from '../../../static/contract/createContract'
import contractAddress from '../../../static/contract/contractAddress'

import {MessagePormpt} from '../../Js/common'
export default {
  components: {
    Upload,
    DropDown,
    Select
  },
  data () {
    return {
      msg: 'msg',
      mintWorkUrl: '',
      mintWorkUrlUpload: '',
      maxsize: 100,
      fromMint: 'mint',
      MintName: '',
      MintDesc: '',
      selectData: [],
      agreementData: [],
      chainID: 0,
      agreementID: 0,
      classData: [],
      classID: 0,
      MaxNumber: 0,
      MintNum: '',
      typeData: [
        {
          trait_type: '',
          value: '',
          addFlag: true
        }
      ],
      leavelData: [
        {
          name: '',
          minNum: 1,
          maxNum: 5,
          addFlag: true
        }
      ],
      langType: localStorage.getItem('language')
    }
  },
  created () {
    this.web3 = initWeb3()
    let contractObj = initContract()
    console.log(contractObj, this.web3, contractAddress) // 合约初始化
    this.ImeetERC721Contract = contractObj.ImeetERC721Contract
    console.log(this.ImeetERC721Contract)
    this.pageInit()
  },
  methods: {
    pageInit: function () {
      this.getChainListData()
      this.getArtWorksTypelist()
    },
    // 获取公链列表
    getChainListData: function () {
      this.$loading.show()
      this.$Api.Common.getChainList()
        .then((res) => {
          this.$loading.hide()
          // console.log(res, 'hundleOnlyCreate,res', JSON.stringify(res))
          if (res && res.code === 200) {
            this.selectData = res.data
          }
        })
        .catch((err) => {
          this.$loading.hide()
          console.log(err, 'hundleOnlyCreate,err', JSON.stringify(err))
        })
    },
    // 获取艺术品分类
    getArtWorksTypelist: function () {
      this.$loading.show()
      this.$Api.Common.getArtWorksTypelist()
        .then((res) => {
          this.$loading.hide()
          // console.log(res, 'hundleOnlyCreate,res', JSON.stringify(res))
          if (res && res.code === 200) {
            this.classData = res.data
          }
        })
        .catch((err) => {
          this.$loading.hide()
          console.log(err, 'hundleOnlyCreate,err', JSON.stringify(err))
        })
    },
    /**
     * 获取协议列表
     * @param {id} 公链ID
    */
    getAgreementByChainId: function () {
      this.$loading.show()
      const params = {
        publicChainID: this.chainID
      }
      this.$Api.Common.getAgreementByChainId(params)
        .then((res) => {
          this.$loading.hide()
          // console.log(res, 'hundleOnlyCreate,res', JSON.stringify(res))
          if (res && res.code === 200) {
            this.agreementData = res.data
          }
        })
        .catch((err) => {
          this.$loading.hide()
          console.log(err, 'hundleOnlyCreate,err', JSON.stringify(err))
        })
    },
    getSelectValue: function (val) {
      console.log(val)
      this.agreementID = val.ID
      this.MaxNumber = val.MaxNumber
    },
    getImgUrl: function (file) {
      console.log(file, ';;;;')
      this.submitFile(file)
    },
    // 上传作品
    submitFile: function (file, type) {
      this.$loading.show()
      let data = new FormData()
      data.append('file', file.file)
      const params = {
        data,
        headers: {
          'content-type': 'multipart/form-data'
        }
      }
      this.$Api.Index.UploadFile(params)
        .then(res => {
          this.$loading.hide()
          if (res && res.code === 200) {
            this.mintWorkUrl = `${process.env.BASE_URL}/${res.data}`
            this.mintWorkUrlUpload = res.data
          } else {
            console.log('upload faile')
            Message('upload file faile')
          }
        })
        .catch(err => {
          this.$loading.hide()
          console.log(err, JSON.stringify(err))
        })
    },
    checkMintNum: function () {
      if (Number(this.MintNum) > Number(this.MaxNumber)) {
        if (this.langType === 'zh-cn') {
          alert('您铸造的数量大于可铸造最大量')
          this.$refs.mintNum.focus()
          return false
        }
        if (this.langType === 'en') {
          alert('You have minted more than the maximum amount that can be minted')
          this.$refs.mintNum.focus()
          return false
        }
        if (this.langType === 'ru') {
          alert('Вы отчеканили больше, чем максимальное количество, которое можно отчеканить')
          this.$refs.mintNum.focus()
          return false
        }
        if (this.typeData === 'zh-tw') {
          alert('您鑄造的數量大於可鑄造最大量')
          this.$refs.mintNum.focus()
          return false
        }
        // this.$refs.mintNum.focus()
        // return false
      }
    },
    hundleCreate: function (type) {
      if (this.MintName === '') {
        // Message.warning('您还未输入名字')
        let langObj = {
          zh_cn: '您还未输入名字',
          en: `You haven't entered your name`,
          ru: 'Вы не ввели имя',
          zh_tw: '您還未鍵入名字'
        }
        MessagePormpt(this.langType, langObj)
        return false
      }
      if (this.MintDesc === '') {
        // Message.warning('您还未输入描述信息')
        let langObj = {
          zh_cn: '您还未输入描述信息',
          en: 'You have not entered a description',
          ru: 'Вы не ввели описание',
          zh_tw: '您還未鍵入描述信息'
        }
        MessagePormpt(this.langType, langObj)
        return false
      }
      const params = {
        image_url: this.mintWorkUrlUpload,
        name: this.MintName,
        description: this.MintDesc,
        public_chain_id: Number(this.chainID),
        scheme_id: Number(this.agreementID),
        class_id: Number(this.classID),
        hold_number: Number(this.MintNum),
        metadata: btoa(encodeURI(JSON.stringify(this.typeData)))
      }
      this.createSubmit(params, type)
    },
    createSubmit: function (params, type) {
      this.$loading.show()
      this.$Api.Works.createPersonWorks(params)
        .then((res) => {
          this.$loading.hide()
          console.log(res, 'hundleOnlyCreate,res', JSON.stringify(res))
          if (res && res.code === 200) {
            this.submitMint(res.data, type)
            // let path = ''
            // if (type === 0) {
            //   path = '/details'
            //   this.$router.push({
            //     path: path,
            //     query: {
            //       artId: res.data.id,
            //       from: 'mint'
            //     }
            //   })
            // } else {
            //   // path = '/sell'
            //   this.submitMint(res.data)
            // }
          }
        })
        .catch((err) => {
          this.$loading.hide()
          console.log(err, 'hundleOnlyCreate,err', JSON.stringify(err))
        })
    },
    submitMint: function (data, type) {
      const _this = this
      _this.ImeetERC721Contract.methods.mint(data.tokenID)
        .send({from: _this.$cookies.get('wallet_acount')})
        .on('transactionHash', function(hash) {
          console.log(hash)
          let path = ''
          if (type === 0) {
            path = '/details'
          } else {
            path = '/sell'
          }
          _this.$router.push({
            path: path,
            query: {
              artId: data.id,
              from: 'mint'
            }
          })
        })
        .on('error', function(error, receipt) {
          console.log(error, 'transactionHash', JSON.stringify(error))
          console.log(receipt, 'transactionHash', JSON.stringify(receipt))
        })
    },
    hundleCreateAndSell: function () {
      console.log(this.typeData)
    },
    getSelectVal: function (val) {
      console.log(val)
      this.chainID = val.ID
      this.getAgreementByChainId()
    },
    getClassSelectVal: function (val) {
      console.log(val)
      this.classID = val.ID
    },
    addTypeItem: function () {
      this.typeData.unshift({
        trait_type: '',
        value: '',
        addFlag: false
      })
      console.log(this.typeData)
    },
    delTypeItem: function (item, i) {
      if (this.typeData.length === 1) {
        this.typeData = [
          {
            trait_type: '',
            value: '',
            addFlag: true
          }
        ]
      } else {
        this.typeData.splice(i, 1)
      }
    },
    addLeavelItem: function () {
      this.leavelData.unshift({
        name: '',
        minNum: 1,
        maxNum: 5,
        addFlag: false
      })
      console.log(this.leavelData)
    },
    delLeavelItem: function (item, i) {
      if (this.leavelData.length === 1) {
        this.leavelData = [
          {
            name: '',
            minNum: 1,
            maxNum: 5,
            addFlag: true
          }
        ]
      } else {
        this.leavelData.splice(i, 1)
      }
    }
  }
}
</script>
<style lang="less" scoped>
  .mint {
    width: 85%;
    .mint_left {
      .upload {
        width: 80%;
        height: 300px;
        margin: 20px 0 0;
      }
      .uploadTips {
        width: 80%;
        margin: 20px 0 0;
      }
    }
    .mint_right {
      .art_item {
        .inputItem {
          // input {
          //   background: none;
          //   width: 100%;
          // }
          /deep/.el-textarea {
            /deep/.el-textarea__inner {
              background: none;
              width: 100%;
            }
          }
          // textarea {
          //   background: none;
          //   width: 100%;
          // }
        }
      }
      .mint_btn {
        .mint_btn_item {
          button {
            width: 100%;
          }
          .el-button--primary {
            background: #7de9ff;
            border: none;
          }
        }
      }
      input {
        background: none;
        width: 100%;
      }
      input::-webkit-input-placeholder{ /* 使用webkit内核的浏览器 */
        color: #d6d6d6;
      }
      input:-moz-placeholder{ /* Firefox版本4-18 */
        color: #d6d6d6;
      }
      input::-moz-placeholder{ /* Firefox版本19+ */
        color: #d6d6d6;
      }
      input:-ms-input-placeholder{ /* IE浏览器 */
        color: #d6d6d6;
      }
      .bg-d8 {
        background: #d8d8d8;
        height: 29px;
        margin: 4px auto;
      }
    }
  }
  /deep/.el-textarea__inner {
    background: none;
    border: none;
    color: #d6d6d6;
  }
  .uploaded-picture{
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
</style>
